#!/usr/bin/env python3
# coding: utf-8

import os.path
import sys
import subprocess
import os
import fcntl
import pty


sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
from tst_lib.ts_common import MyTestCase


class PythonTestCase(MyTestCase):
    """
    @用例ID: 20230521-200715-714024011
    @用例名称: haiku_test
    @用例级别: 3
    @用例标签:
    @用例类型: 功能
    """

    def tc_setup(self, *args):
        # @预置条件:
        self.msg("this is tc_setup")

    def do_test(self, *args):
        def set_no_block_read(output):
            fd = output.fileno()
            fl = fcntl.fcntl(fd,fcntl.F_GETFL)
            fcntl.fcntl(fd,fcntl.F_SETFL,fl | os.O_NONBLOCK)

        def try_read(output):
            try:
                return output.readline()
            except:
                return b''
        
        qemu_dir = os.environ.get('QEMU_SRC') #QEMU源码路径
        self.assert_true(qemu_dir != '')
        master_fd, slave_fd = pty.openpty()
        env = os.environ.copy()
        env['DEBUG'] = '1'
        process = subprocess.Popen(['make','vm-build-haiku.x86_64'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=slave_fd,cwd=qemu_dir,env=env)
        set_no_block_read(process.stdout)
        set_no_block_read(process.stderr)
        # @测试步骤: 构建qemu
        # @预期结果: qemu构建成功
        while True:
            output = try_read(process.stdout).decode('utf-8')
            if output == '' and process.poll() is not None:
                break
            if output:
                self.msg(output)
                if 'cd $(mktemp -d /tmp/qemu-test.XXXXXX);' in output:
                    # 出现这句说明已经准备在虚拟机中进行构建QEMU了，说明功能正常
                    self.msg('已经进入系统,测试终止')
                    os.system('pkill -9 -s {}'.format(process.pid))
                    return
            errout = try_read(process.stderr).decode('utf-8')
            if errout :
                self.msg(errout)
                if 'cd $(mktemp -d /tmp/qemu-test.XXXXXX);' in errout:
                    # 出现这句说明已经准备在虚拟机中进行构建QEMU了，说明功能正常
                    self.msg('已经进入系统,测试终止')
                    os.system('pkill -9 -s {}'.format(process.pid))
                    return
        return_code = process.wait()
        self.assert_true(return_code == 0)

    def tc_teardown(self, *args):
        self.msg("this is tc_teardown")


if __name__ == '__main__':
    PythonTestCase().tst_main(sys.argv)
